import time
from win32 import win32gui

import win32con
import win32com.client

import pyperclip


def get_window_class_name(hwnd):
    """获取窗口类名"""

    if not hwnd:
        return

    try:
        return win32gui.GetClassName(hwnd)
    except Exception as e:
        return ""


# 获取剪贴板内容
def get_clipboard_text(retry=5):
    try:
        return pyperclip.paste()
    except Exception as e:
        time.sleep(0.1)
        if retry > 0:
            return get_clipboard_text(retry - 1)
        else:
            raise e


def is_valid_wechat_window(hwnd):
    """判断是否是有效的微信窗口"""

    return "WeChatMainWndForPC" == get_window_class_name(hwnd)


def show_window(hwnd, op="normal"):
    """显示窗口"""
    """op: normal 默认大小, max 最大化, min 最小化"""

    if not hwnd:
        return

    shell = win32com.client.Dispatch("WScript.Shell")
    shell.SendKeys("%")
    if op == "max":
        win32gui.ShowWindow(hwnd, win32con.SW_SHOWMAXIMIZED)
    elif op == "normal":
        win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL)
    elif op == "min":
        win32gui.ShowWindow(hwnd, win32con.SW_SHOWMINIMIZED)

    win32gui.SetForegroundWindow(hwnd)

    time.sleep(0.1)


def max_window(hwnd):
    """最大化窗口"""

    show_window(hwnd, "max")


def close_window(hwnd):
    """关闭窗口"""

    if not hwnd:
        return

    # 如果hwnd是list,则循环关闭
    if isinstance(hwnd, list):
        for h in hwnd:
            close_window(h)
        return

    shell = win32com.client.Dispatch("WScript.Shell")
    shell.SendKeys("%")
    win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)

    time.sleep(1)


def find_window_hwnd_list_by_title(title: str):
    """获取指定title的窗口句柄列表"""

    all_hwnd_list = []
    win32gui.EnumWindows(lambda hWnd, param: param.append(hWnd), all_hwnd_list)

    valid_hwnd_list = []

    for hwnd in all_hwnd_list:
        if (
            win32gui.IsWindow(hwnd)
            and win32gui.IsWindowEnabled(hwnd)
            and win32gui.IsWindowVisible(hwnd)
        ):
            valid_hwnd_list.append(hwnd)

    # 筛选指定title的窗口
    hWnd_list = [
        hWnd for hWnd in valid_hwnd_list if title == win32gui.GetWindowText(hWnd)
    ]

    return hWnd_list


def find_window_hwnd_first(title: str):
    """获取指定title的窗口句柄"""

    hWnd_list = find_window_hwnd_list_by_title(title)

    if not hWnd_list:
        return None

    return hWnd_list[0]


def kill_process_by_name(process_name: str):
    """杀死所有名称为process_name的进程"""

    import os

    # 通过进程名称杀死进程
    os.system(f"taskkill /f /im {process_name}")


def finw_window_hwnd_list_by_classname(classname: str):
    """获取指定classname的窗口句柄"""

    all_hwnd_list = []
    win32gui.EnumWindows(lambda hWnd, param: param.append(hWnd), all_hwnd_list)

    valid_hwnd_list = []

    for hwnd in all_hwnd_list:
        if (
            win32gui.IsWindow(hwnd)
            and win32gui.IsWindowEnabled(hwnd)
            and win32gui.IsWindowVisible(hwnd)
        ):
            valid_hwnd_list.append(hwnd)

    # 筛选指定title的窗口
    hWnd_list = [
        hWnd for hWnd in valid_hwnd_list if classname == get_window_class_name(hWnd)
    ]

    if not hWnd_list:
        return None

    return hWnd_list
